/**
 * this files imports or updates exisiting entries with pubchem compound properties
 */

import edu.ucdavis.genomics.metabolomics.binbase.connector.references.pubchem.PubchemCompoundSDFResolver
import org.apache.log4j.Logger
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.InchFinder
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.SdfToInchi

//configuration file
def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

Logger logger = Logger.getLogger("ImportPubchem")

logger.info("starting import/update of the pubchem compound data")

String tempDir = config.files.pubchem.compound

FileHelper.workOnDir(tempDir, {File file ->
  PubchemInchiCompound sub = new PubchemInchiCompound()
  SdfToInchi.sdfToInchi(new FileInputStream(file), sub)

}, logger, ".sdf")

class PubchemInchiCompound implements InchFinder {

  private def setCompoundProperties(PubchemCompoundSDFResolver resolver, Compound compound) {
    Double exactMass = resolver.getExactMass()
    Double molareMass = resolver.getMolecularWeight()
    String molecularFormula = resolver.getMolecularFormula();

    if (molareMass != null) {
      if (molareMass > 0) {
        compound.molareMass = molareMass
      }
    }
    if (exactMass != null) {
      if (exactMass > 0) {
        compound.exactMolareMass = exactMass
      }
    }
    if (molecularFormula != null) {
      compound.formula = molecularFormula
    }
  }

  public void foundInchi(String myInchi, Map<java.lang.Object, java.lang.Object> objectObjectMap) throws Exception {
    Logger logger = Logger.getLogger("ImportPubchem")
    logger.debug "checking if inchi is acceptable"

    logger.debug "checking if inchi is acceptable"
    if (myInchi != null && myInchi.size() > 0) {

      PubchemCompoundSDFResolver resolver = new PubchemCompoundSDFResolver();

      resolver.prepare(objectObjectMap)

      //logger.debug "loading compound from library ${resolver.getInchi()}"
      Compound compound = CompoundHelper.getCompound(resolver.getInchi(),resolver.getInchiKey(),logger)

      setCompoundProperties(resolver, compound)

      CompoundHelper.updateCID(PubchemCompound.findByCompound(compound), logger, compound, resolver)

      //work on the smile codes
      CompoundHelper.updateSmiles(resolver.getIsoSmile(), compound, true)
      CompoundHelper.updateSmiles(resolver.getCanSmile(), compound, false)

      //work on iupac names
      List<String> iupacs = new Vector<String>()

      if (resolver.iupacCasName != null) {
        for (String s: resolver.iupacCasName) {
          if (!iupacs.contains(s)) {
            iupacs.add(s)
          }
        }
      }

      if (resolver.iupacName != null) {

        for (String s: resolver.iupacName) {
          if (!iupacs.contains(s)) {
            iupacs.add(s)
          }
        }
      }

      if (resolver.iupacSystematicName) {
        for (String s: resolver.iupacSystematicName) {
          if (!iupacs.contains(s)) {
            iupacs.add(s)
          }
        }
      }

      if (resolver.iupacTraditionalName) {
        for (String s: resolver.iupacTraditionalName) {
          if (!iupacs.contains(s)) {
            iupacs.add(s)
          }
        }
      }

      CompoundHelper.updateIUPACNames(iupacs, compound, logger)

      //save the compound again
      compound = CompoundHelper.saveCompound(compound, logger)

    }
  }
}